package com.example.sm.mycook;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.sm.mycook.db.SQLiteUtils;

import java.util.List;

public class AddressActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mAddressBack;
    private ImageView mAddressAdd;
    private ListView mListView;
    private Address_adapter adapter;
    private List<User> list;

    private SQLiteUtils sql;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        sql = new SQLiteUtils(this);
        list = sql.selectAllData();
        initView();
    }

    private void initView() {
        mAddressBack = (ImageView) findViewById(R.id.address_back);
        mAddressAdd = (ImageView) findViewById(R.id.address_add);
        mListView = (ListView) findViewById(R.id.address_listView);

        adapter = new Address_adapter(list, this);

        mListView.setAdapter(adapter);


        mAddressBack.setOnClickListener(this);
        mAddressAdd.setOnClickListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent();
                intent.putExtra("address",list.get(position).getAddress());
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.address_back:
                finish();
                break;
            case R.id.address_add:
                startActivityForResult(new Intent(this, AddressMessageActivityd.class), 0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            User user = (User) bundle.getSerializable("user");
            sql.InsertData(user.tid,user.name,user.phone,user.type,user.address,user.path,user.check);
            list = sql.selectAllData();
            adapter.AddData(list);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sql != null) {
            sql.getHelper().close();
            sql.getDB().close();
        }
    }
}
